//
//  CLDistrictSelectVC.m
//  togetherLBS
//
//  Created by Phyllis Hu on 15-5-23.
//  Copyright (c) 2015年 celi. All rights reserved.
//

#import "CLDistrictSelectVC.h"
#import <CoreLocation/CoreLocation.h>
#import "CountryInfo.h"
#import "pinyin.h"
#import "CLInfoSelectVC.h"
#import "CLDeviceiOSLocationTool.h"
#import "CLDeviceIOS.h"

@interface CLDistrictSelectVC ()<CLDeviceiOSLocationToolDelegate>
@property (nonatomic, strong) NSArray *countryInfos;
@property (nonatomic, strong) NSMutableArray *selection;
@property (nonatomic, strong) CLDeviceiOSLocationTool *locationTool;
@property (nonatomic, copy) NSString *fid;
/**
 *  定位的地理位置
 */
@property (nonatomic, copy) NSString* locationName;

@end

@implementation CLDistrictSelectVC

- (NSString*)locationName{
    
    if (_locationName == nil) {
        _locationName = [NSString string];
        _locationName = CLLocalizedString(@"isLocation", nil);
    }
    return _locationName;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = CLLocalizedString(@"district", nil);
    self.clearsSelectionOnViewWillAppear = NO;
    
    self.locationTool = [CLDeviceiOSLocationTool CLLocationManagerWithLocationAccuracyType:kCLLocationAccuracyNearestTenMeters];
    [self.locationTool startLocation];
    self.locationTool.locationDelegate = self;
    
}

- (NSArray *)countryInfos
{
    if (_countryInfos == nil) {
        NSString *countInfoPath = [[NSBundle mainBundle] pathForResource:@"countryInfo.plist" ofType:nil];
        
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:countInfoPath];
        NSMutableArray *countryArray = [NSMutableArray array];
        
        for (NSDictionary *dict in dictArray) {
            CountryInfo *countryInfo = [CountryInfo countryInfoWithDict:dict];
            countryInfo.subTitle = @"";
            [countryArray addObject:countryInfo];
        }
        
        // 对已经得到的国家进行排序
        NSMutableArray *sortArray = nil;
        if (![CLDeviceIOS isChineseLanguageType])
        { // 按照英文排序
            sortArray = [self sortArrayWithEnglish:countryArray];
        } else {
            sortArray = [self sortArrayWithPinYin:countryArray];
        }
  
        if(_country.length > 0){
            CountryInfo* firstCountry = [[CountryInfo alloc]init];
            firstCountry.subTitle = CLLocalizedString(@"selectedDis", nil);
            for(CountryInfo* info in sortArray){
                if (([info.name_cn isEqualToString:_country])||([info.name_en isEqualToString:_country])){
                    firstCountry.name_cn = info.name_cn;
                    firstCountry.name_en = info.name_en;
                    firstCountry.phone_code = info.phone_code;
                    firstCountry.time_difference = info.time_difference;
                    firstCountry.time_zone = info.time_zone;
                    firstCountry.sub = info.sub;
                    firstCountry.pinYin = info.pinYin;
                    break;
                }
            }
            [sortArray insertObject:firstCountry atIndex:0];
        }
        _countryInfos = sortArray;
    }
    return _countryInfos;
}

- (NSMutableArray *)sortArrayWithPinYin:(NSArray *)array
{
    // 获取字符串中文字的拼音首字母并与字符串共同存放
    NSMutableArray *countryInfosArray=[NSMutableArray array];
    
    for(int i = 0; i < [array count]; i++){
        
        CountryInfo *countryInfo = array[i];
        
        if(countryInfo.name_cn == nil){
            countryInfo.name_cn = @"";
        }
        
        if(![countryInfo.name_cn isEqualToString:@""]){
            
            NSString *pinYinResult=[NSString string];
            
            for(int j = 0; j < countryInfo.name_cn.length;j++){
                
                NSString *singlePinyinLetter=[[NSString stringWithFormat:@"%c",pinyinFirstLetter([countryInfo.name_cn characterAtIndex:j])]uppercaseString];
                
                pinYinResult=[pinYinResult stringByAppendingString:singlePinyinLetter];
            }
            countryInfo.pinYin=pinYinResult;
            
        }else{
            
            countryInfo.pinYin=@"";
        }
        
        [countryInfosArray addObject:countryInfo];
    }
    
    // 按照拼音首字母对这些Strings进行排序
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pinYin" ascending:YES]];
    [countryInfosArray sortUsingDescriptors:sortDescriptors];
    
    return countryInfosArray;
}

- (NSMutableArray *)sortArrayWithEnglish:(NSArray *)array
{
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:array];
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name_en" ascending:YES]];
    [tempArray sortUsingDescriptors:sortDescriptors];
    return tempArray;
}

- (NSMutableArray *)selection
{
    if (_selection == nil) {
        _selection = [NSMutableArray array];
    }
    return _selection;
}
    
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return self.countryInfos.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell* cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.textLabel.text = self.locationName;
        cell.imageView.image = [UIImage imageNamed:@"pin_center"];
        return cell;
    }
    
    static NSString *cellID = @"districtCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    
    CountryInfo *countryInfo = self.countryInfos[indexPath.row];
    
    if ([countryInfo.sub count] > 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    if (![CLDeviceIOS isChineseLanguageType])
    {
        cell.textLabel.text = countryInfo.name_en;
    } else {
        cell.textLabel.text = countryInfo.name_cn;
    }
    cell.detailTextLabel.text = countryInfo.subTitle;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CLLocalizedString(@"getLocation", nil);
    }else{
        return CLLocalizedString(@"allDis", nil);
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    CountryInfo *countryInfo = self.countryInfos[indexPath.row];
    
    if (self.selection.count > 0) {
        [self.selection removeLastObject];
    }

    // 添加当前的选择行
    if (indexPath.section == 0) {
        NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@" "];
        NSArray *theArray = [cell.textLabel.text componentsSeparatedByCharactersInSet:cSet];
        if([cell.textLabel.text isEqualToString:CLLocalizedString(@"isLocation", nil)]) return;
        for (NSString *str in theArray) {
            [self.selection addObject:str];
        }
    }else{
        [self.selection addObject:cell.textLabel.text];
    }

    // 是否有下一级地区
    if ((countryInfo.sub.count < 2)|| (indexPath.section == 0)) {

        DLog(@"发送网络请求 设置地区")
        // 更改数据成功后
        self.block(self.selection);
        [self.navigationController popViewControllerAnimated:YES];
            //发送网络请求
            /*CLMemberSettingParam *param = [CLMemberSettingParam param];
            param.fid = self.fid;
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            dict[@"country"] = self.selection[0];
            if (self.selection.count > 1) {
                dict[@"province"] = self.selection[1];
            }
            if (self.selection.count > 2) {
                dict[@"city"] = self.selection[2];
            }
            param.district = dict.JSONString;
            
            [CLMemberTool setMemberInfoWithParam:param success:^(CLBaseResult *result) {
                if (result.r.integerValue == 1) {
                    // 更改数据成功后
                    self.block(self.selection);
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    [CLService showAlertWithMessage:result.errorMessage];
                }
            } failure:^(NSError *error) {
                
            }];*/
      
    } else {
        // 跳入下一级菜单
        CLInfoSelectVC *selectVC = [[CLInfoSelectVC alloc] initWithData:countryInfo.sub selectionData:self.selection];
        selectVC.block = self.block;
        selectVC.index = 1;
        [self.navigationController pushViewController:selectVC animated:YES];
    }
}

- (void)CLDeviceiOSLocationName:(CLPlacemark *)placemark{
 
     _locationName = [NSString stringWithFormat:@"%@ %@ %@",placemark.country,placemark.administrativeArea,placemark.locality];
   NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil]  withRowAnimation:UITableViewRowAnimationNone];

}

@end
